<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-tree
          :data="list"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- 作用域插槽 data拿到的是每一个子节点的对象 -->
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="getDialog(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="redDialog(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delDialog(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="30%"
      @close="AddDialog"
      @open="fetchmanager"
    >
      <template #default>
        <el-form ref="addform" label-width="120px" :model="Form" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="Form.name" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="Form.code" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="Form.manager" placeholder="请选择">
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="Form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.prevent="getadd">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDepart, getEmployeeSimple, getaddment, fetchred, updateDepartments, delDepartments } from '@/api/depart'
import treeArray from '@/utils/transTree'
export default {
  name: 'Depart',
  data() {
    // const ruelsment = async(rule, vaule, callback) => {
    //   const res = await fetchDepart()
    //   const arr = []
    //   res.depts.forEach(item => {
    //     arr.push(item.code)
    //   })
    //   if (arr.includes(vaule)) {
    //     callback(new Error('编码不能重复'))
    //   } else {
    //     callback()
    //   }
    // }
    const code = (rule, value, callback) => {
      // 1. 声明一个空的codeList
      // 2. 判断当前是编辑还是新增 如果是新增 codelist就存放所有的code码
      // 如果是编辑状态 先把当前项已经回填的code从所有的codelist中删除 创建一个新的复制一份 删除这一份
      // 不要删除form里的 code 因为双向绑定 再赋值给codeList
      // 3. 开始使用数组的includes方法进行判断
      let codeList = []
      if (!this.Form.id) {
        codeList = this.codelist
      } else {
        codeList = this.codelist.filter(code => code !== this.cacheCode)
      }
      if (codeList.includes(value)) {
        callback(new Error('重复啦，请换一个'))
      } else {
        callback()
      }
    }
    return {
      list: [{
        name: '财务部',
        children: [
          {
            name: '财务核算部'
          },
          {
            name: '税务核算部'
          }
        ]
      }],
      defaultProps: {
        label: 'name'
      },
      dialogVisible: false,
      managerList: [],
      codelist: [],
      cacheCode: null,
      Form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      rules: {
        code: [
          { required: true, message: '部门编码必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50字符', trigger: 'blur' },
          { trigger: 'blur', validator: code }
        ],
        name: [
          { required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50字符', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getment()
  },
  methods: {
    async getment() {
      const res = await fetchDepart()
      // 目标：把后端返回的平铺的数组转化为数组需要的树形结构
      this.list = treeArray(res.depts)
      res.depts.forEach(item => {
        this.codelist.push(item.code)
      })
    },
    // 重置数据
    removeDialog() {
      this.Form = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
    },
    getDialog(id) {
      this.Form.pid = id
      this.dialogVisible = true
    },
    AddDialog() {
      this.dialogVisible = false
      this.removeDialog()
    },
    async  fetchmanager() {
      const res = await getEmployeeSimple()
      this.managerList = res
    },
    getadd() {
      this.$refs.addform.validate(async valid => {
        if (!valid) return
        if (this.Form.id) {
          // 有id就调用编辑
          await updateDepartments(this.Form)
        } else {
          await getaddment(this.Form)
        }
        this.getment()
        this.$message.success(`${this.Form.id ? '修改' : '新增'}成功`)
        this.dialogVisible = false
        this.$refs.addform.resetFields()
      })
    },
    // 数据回填
    async redDialog(id) {
      this.dialogVisible = true
      const res = await fetchred(id)
      this.Form = res
      // 获取当前数据回填input里的code值
      this.cacheCode = res.code
    },
    // 删除列表
    delDialog(id) {
      this.$confirm('确定要删除吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartments(id)
        this.$message.success('删除成功')
        this.getment()
      }).catch(() => {
      })
    }
  }
}
</script>
